<template>
  <PageWrapper v-loading="loading" loading-tip="加载中...">
    <div class="p-4 p-4-tag">
      <div class="tag">
        <BasicTable @register="registerTable">
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'action'">
              <TableAction
                :actions="[
                  {
                    label: '编辑',
                    icon: 'ant-design:edit-outlined',
                    ifShow: hasPermission('12-4-1-update'),
                    onClick: handleUpdate.bind(null, record),
                  },
                  {
                    label: '删除',
                    icon: 'ant-design:delete-outlined',
                    ifShow: hasPermission('12-4-1-del'),
                    onClick: handleDelete.bind(null, record),
                  },
                ]"
              />
            </template>
          </template>
          <template #toolbar>
            <a-button type="primary" @click="handleAdd" v-if="hasPermission('12-4-1-add')">
              新增
            </a-button>
            <a-button type="primary" @click="handleSave" v-if="hasPermission('12-4-1-save')">
              保存到配置文件
            </a-button>
          </template>
        </BasicTable>
      </div>
    </div>
    <modelByDetail
      @register="registerByDetail"
      @submit-success="handleUpdateTable"
      :info="detailForm"
    />
  </PageWrapper>
</template>

<script setup lang="ts">
  import { usePermission } from '/@/hooks/web/usePermission';
  import { PageWrapper } from '/@/components/Page';
  import { BasicTable, TableAction, useTable } from '/@/components/Table';
  import { BasicColumn } from '/@/components/Table/src/types/table';
  import modelByDetail from '/@/views/project/database/components/modelByDetail.vue';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useI18n } from '/@/hooks/web/useI18n';

  import { getdbconfiginfo, deldbconfig, saveconfig } from '/@/api/resource/index';
  import { ref, onMounted, reactive, h } from 'vue';

  let loading = ref<boolean>(false);
  const { hasPermission } = usePermission();
  let detailForm = reactive({
    type: 'add',
    data: {},
  });
  // 表单数据
  let columns: BasicColumn[] = [
    {
      title: '名称',
      dataIndex: 'Name',
    },
    {
      title: '服务地址',
      dataIndex: 'ServerUrl',
    },
    {
      title: '端口号',
      dataIndex: 'Port',
    },
    {
      title: '账号',
      dataIndex: 'UserName',
    },
  ];
  let actionColumn = {
    width: 100,
    title: '操作',
    dataIndex: 'action',
    // slots: { customRender: 'action' },
  };
  const [registerTable, { getPaginationRef, setPagination, reload }] = useTable({
    title: '',
    api: getdbconfiginfo,
    immediate: false,
    columns,

    actionColumn: hasPermission(['12-4-1-update', '12-4-1-del']) ? actionColumn : undefined,
    canResize: false,
    showIndexColumn: false,
    striped: true,
    bordered: true,
    fetchSetting: {
      pageField: 'PageNO',
      sizeField: 'PageSize',
      totalField: 'TotalRows',
      listField: 'Rows',
    },
    beforeFetch: () => {
      return [
        {
          PageNO: getPaginationRef().current || 1,
          PageSize: getPaginationRef().pageSize || 50,
        },
      ];
    },
  });
  const { createConfirm, createMessage } = useMessage();
  const { t } = useI18n();

  const [registerByDetail, { openModal: openModalByDetail, closeModal: closeModalByDetail }] =
    useModal();
  onMounted(async () => {
    setPagination({
      current: 1,
    });
    reload();
  });

  function handleUpdate(_record) {
    detailForm.type = 'copy';
    detailForm.data = _record;
    openModalByDetail();
  }
  function handleDelete(_record) {
    createConfirm({
      iconType: 'warning',
      okText: '确认',
      title: () => h('span', '温馨提示'),
      content: () => h('span', `是否确认删除该文件（${_record.Name}）`),
      onOk: async () => {
        try {
          let list = _record.FullName.split(`${_record.Name}.`);
          let target = list.length > 0 ? list[0] : '';
          await deldbconfig([target]);
          createMessage.success(t('layout.setting.operatingTitle'));
          reload();
        } catch (error) {}
      },
    });
  }
  function handleUpdateTable() {
    closeModalByDetail();
    setTimeout(() => {
      reload();
    }, 250);
  }
  function handleAdd() {
    detailForm.type = 'add';
    detailForm.data = {};
    openModalByDetail();
  }
  function handleSave() {
    createConfirm({
      iconType: 'warning',
      title: () => h('span', '温馨提示'),
      okText: '确认',
      content: () => h('span', `此操作将会把页面内容保存到配置文件，是否确认该操作？`),
      onOk: async () => {
        try {
          await saveconfig();
          createMessage.success(t('layout.setting.operatingTitle'));
        } catch (error) {}
      },
    });
  }
</script>
<script lang="ts">
  export default {
    name: 'ResourceDatabase',
  };
</script>
<style lang="less" scoped>
  .p-4-tag {
    width: 100%;
    height: 100%;
    padding: 0px !important;

    .tag {
      position: relative;
      overflow: hidden;
      height: 100%;
      background-color: #fff;
    }
  }
</style>
